package com.itcast.yygh.orders.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class OrderDelayQueueConfig {

    public static final String ORDER_DELAY_QUEUE = "order.delay.queue";
    public static final String ORDER_DELAY_EXCHANGE = "order.delay.exchange";
    public static final String ORDER_DELAY_ROUTING_KEY = "order.delay.routing.key";

    // 延迟队列
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> args = new HashMap<>();
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称
        args.put("x-dead-letter-exchange", "exchange.direct.order");
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称
        args.put("x-dead-letter-routing-key", "order");
        // 设置TTL为15分钟(900000毫秒)
        args.put("x-message-ttl", 900000);
        return QueueBuilder.durable(ORDER_DELAY_QUEUE).withArguments(args).build();
    }

    // 普通交换机
    @Bean
    public Exchange orderDelayExchange() {
        return ExchangeBuilder.directExchange(ORDER_DELAY_EXCHANGE).durable(true).build();
    }

    // 绑定关系
    @Bean
    public Binding orderDelayBinding() {
        return BindingBuilder
                .bind(orderDelayQueue())
                .to(orderDelayExchange())
                .with(ORDER_DELAY_ROUTING_KEY)
                .noargs();
    }
}
